package com.atom.common.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import org.apache.log4j.Logger;

/**
 * Description:鉴于SimpleDateFormat和DateFormat类不是线程安全的，
 * @author paddy
 * @date 2015年12月31日 下午2:53:15
 */
public class DateUtil {
  
  private static Logger logger = Logger.getLogger(DateUtil.class);

  public static Date parseTime(String date){
    if(date==null || date.length()<=0)
      return null;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date result = null;
    try {
      result = sdf.parse(date);
    } catch (ParseException e) {
      logger.error("error message = {}" + e.getMessage(), e);
    }
    return result;
  }

  public static Date parseDate(String date){
    if(date==null || date.length()<=0)
      return null;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date result = null;
    try {
      result = sdf.parse(date);
    } catch (ParseException e) {
      logger.error("error message = {}" + e.getMessage(), e);
    }
    return result;
  }

  public static String formatTime(Date date) {
    if (date != null) {
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
      return simpleDateFormat.format(date);
    } else {
      return "";
    }
  }
  
  public static String formatTimeWithoutSpace(Date date) {
    if (date != null) {
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss");  
      return simpleDateFormat.format(date);
    } else {
      return "";
    }
  }

  public static String formatDate(Date date) {
    if (date != null) {
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");  
      return simpleDateFormat.format(date);
    } else {
      return "";
    }
  }

  /**
   * 
   * Description: 将日期增加若干小时
   * @param start 初始时间
   * @param num 增加num小时
   * @return
   */
  public static Date add(Date start, int num){
    Calendar cld = Calendar.getInstance(Locale.CHINA);
    cld.setTime(start);
    cld.add(Calendar.HOUR, num);
    return cld.getTime();
  }
}
